﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Security.AccessControl;

namespace fm2
{
	public class FileItem : IItemElement<FileItem>, IComparable<FileItem>
	{
		public string Time { get; set; }
		public string Name { get; set; }
		public string Owner { get; set; }
		public long Size { get; set; }
		public StatusElement Status { get; set; }
		public bool _Selected { get; set; }
		public bool _AddToLog { get; set; }

		public FileItem(string fname)
		{
			FileInfo finfo = new FileInfo(fname);
			Time = finfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
			Size = finfo.Length;
			Name = finfo.FullName;
			try {
				Owner = finfo.GetAccessControl().GetOwner(typeof(System.Security.Principal.NTAccount)).Value;
			} catch (System.Security.Principal.IdentityNotMappedException) {
				Owner = finfo.GetAccessControl().GetOwner(typeof(System.Security.Principal.SecurityIdentifier)).Value;
			} catch (UnauthorizedAccessException) {
				Owner = "No access";
			} catch {
				Owner = "Error";
			}
			Status = StatusElement.Created;
			_AddToLog = true;

			int n = Owner.LastIndexOf('\\') + 1;
			if (n > 1) Owner = Owner.Substring(n);
		}

		public int CompareTo(FileItem item)
		{
			if (Name.CompareTo(item.Name) == 0) {
				if (Size.CompareTo(item.Size) == 0 &&
					Time.CompareTo(item.Time) == 0 &&
					Owner.CompareTo(item.Owner) == 0) {
					return 0;
				}
				return 1;
			}
			return -1;
		}
		
		public void CopyFrom(FileItem item)
		{
			Time = item.Time;
			Owner = item.Owner;
			Size = item.Size;
		}
		
		public override string ToString()
		{
			return Name;
		}
	}
}
